package functionality;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import controller.IRemoteController;
import controller.RemoteController;
import boundary.IMenu;

public class Listener implements Runnable, IListener {

	private IMenu menu;
	private int port;
	
	public Listener(IMenu menu, int port){
		this.menu = menu;
		this.port = port;
	}
	
	/*
	 * Metoden skal oprette en serversocket og lytte på denne. Når en forbindelse modtages
	 * skal der oprettes en IRemoteController i en ny tråd som også skal startes.
	 */
	@Override
	public void run() {
		try ( 
			    ServerSocket serverSocket = new ServerSocket(port);
			    Socket clientSocket = serverSocket.accept();
			    PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
			    BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
			) {
			IRemoteController rC = new RemoteController(menu, in, out);
			Thread t = new Thread((Runnable) rC);
			t.start();	
			t.join();
		
		} catch (IOException | InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
